package com.poetize.plus.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetize.plus.entity.dto.TimeLineDTO;
import com.poetize.plus.entity.dto.page.TimeLinePageDTO;
import com.poetize.plus.entity.po.TimeLine;
import com.poetize.plus.entity.vo.TimeLineVO;
import com.poetize.plus.entity.vo.page.TimeLinePageVO;
import com.poetize.plus.mapper.TimeLineMapper;
import com.poetize.plus.service.TimeLineService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author zuosy
 * @created 2024/5/13 14:21
 */
@Service
@RequiredArgsConstructor
public class TimeLineServiceImpl extends ServiceImpl<TimeLineMapper, TimeLine> implements TimeLineService {

    @Override
    public Page<TimeLinePageVO> timeLinePage(TimeLinePageDTO timeLinePageDTO) {
        Page<TimeLine> linePage = lambdaQuery()
                .between(Objects.nonNull(timeLinePageDTO.getStartTime()) && Objects.nonNull(timeLinePageDTO.getEndTime()),
                        TimeLine::getOccurrenceTime,
                        timeLinePageDTO.getStartTime(),
                        timeLinePageDTO.getEndTime())
                .orderByAsc(TimeLine::getOccurrenceTime)
                .page(Page.of(timeLinePageDTO.getCurrent(), timeLinePageDTO.getSize()));

        return getTimeLinePageVOPage(linePage);
    }

    @Override
    public Boolean addTimeLine(TimeLineDTO timeLineDTO) {
        return baseMapper.insert(TimeLineDTO.convertDTO(timeLineDTO)) > 0;
    }

    @Override
    public TimeLineVO queryById(Long id) {
        TimeLine timeLine = baseMapper.selectById(id);
        return TimeLineVO.convert(timeLine);
    }

    @Override
    public Boolean updateTimeLine(TimeLineDTO timeLineDTO) {
        return baseMapper.updateById(TimeLineDTO.convertDTO(timeLineDTO)) > 0;
    }

    @Override
    public Page<TimeLinePageVO> getPage(TimeLinePageDTO timeLinePageDTO) {
        Page<TimeLine> linePage = lambdaQuery()
                .orderByAsc(TimeLine::getOccurrenceTime)
                .page(Page.of(timeLinePageDTO.getCurrent(), timeLinePageDTO.getSize()));

        return getTimeLinePageVOPage(linePage);
    }

    /**
     * 封装查询数据返回分页
     * @param linePage
     * @return
     */
    private Page<TimeLinePageVO> getTimeLinePageVOPage(Page<TimeLine> linePage) {
        if (CollectionUtils.isEmpty(linePage.getRecords())){
            return new Page<>();
        }
        List<TimeLinePageVO> voList = TimeLinePageVO.convertPageList(linePage.getRecords());
        Page<TimeLinePageVO> result = new Page<>();
        result.setTotal(linePage.getTotal());
        result.setRecords(voList);
        return result;
    }
}
